package com.web.servlet;

import com.alibaba.fastjson2.JSON;
import com.web.JDBCUtils;
import com.web.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author lenovo
 * @Description 根据关键字搜索学生名字的Servlet
 * @Date2025-2-27 19:28
 */

@WebServlet("/searchStudents")
public class SearchStudentsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型为JSON
        resp.setContentType("application/json;charset=utf-8");

        // 从请求参数中获取关键字
        String keyword = req.getParameter("keyword");

        // 检查关键字是否为空
        if (keyword == null || keyword.trim().isEmpty()) {
            // 如果关键字为空，返回空列表
            resp.getWriter().write(JSON.toJSONString(Collections.emptyList()));
            return;
        }

        // 构建SQL查询语句，使用LIKE进行模糊匹配
        String sql = "SELECT * FROM student_s WHERE name LIKE ?";

        // 执行查询，使用关键字进行模糊搜索
        List<Student> students = JDBCUtils.query(Student.class, sql, "%" + keyword + "%");

        // 将查询结果转换为JSON格式
        String jsonResult = JSON.toJSONString(students);

        // 将JSON数据写入响应流
        resp.getWriter().write(jsonResult);
    }
}
